package com.sky.web.app;

import cn.hutool.core.collection.CollectionUtil;
import com.sky.context.UserHolder;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AppAddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    //地址列表
    @GetMapping("/list")
    public Result list() {
        //1.获得登录人id
        Long userId = UserHolder.get();
        //2.封装条件实体
        AddressBook param = AddressBook.builder()
                .userId(userId)
                .build();
        //3.调用service条件查询
        List<AddressBook> list = addressBookService.findList(param);
        //4.返回结果
        return Result.success(list);
    }

    //添加地址
    @PostMapping
    public Result add(@RequestBody AddressBook addressBook) {
        addressBookService.save(addressBook);
        //4.返回结果
        return Result.success();
    }

    //设置默认地址
    @PutMapping("/default")
    public Result setDefault(@RequestBody AddressBook addressBook) {

        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    //查询默认地址
    @GetMapping("/default")
    public Result getDefault() {
        //1. 获取登录用户id
        Long userId = UserHolder.get();
        //2. 封装查询条件
        AddressBook param = AddressBook.builder()
                .userId(userId)
                .isDefault(1)
                .build();
        List<AddressBook> list = addressBookService.findList(param);

        //3. 返回结果
        if (CollectionUtil.isNotEmpty(list)) {
            return Result.success(list.get(0));
        }
        return Result.success("无默认地址");
    }

    //根据id删除地址
    @DeleteMapping
    public Result delete(Long id) {
        addressBookService.deleteById(id);
        return Result.success();
    }

    //根据id查询地址
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Long id) {
        AddressBook addressBook = addressBookService.findById(id);
        return Result.success(addressBook);
    }

    //根据id修改地址
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return Result.success();
    }
}
